<template>
  <div class="container">
    <el-upload
      class="upload-demo"
      action="http://localhost:8181/image/upload"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :limit="1"
      :data="{ name: 'photo' }"
    >
      <el-button size="small" type="primary" @click="clear()">点击上传</el-button>
    </el-upload>
    <div class="image-container">
      <p>图片展现区</p>
      <el-image v-if="imageUrl" :src="imageUrl" fit="contain"></el-image>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: null
    };
  },
  methods: {
    clear(){
      this.imageUrl = null;
    },
    handleSuccess(response, file) {
    // 处理图片上传成功的逻辑
    console.log(file);
    const MAX_WIDTH = 600; // 设置最大宽度为500px
    const MAX_HEIGHT = 400; // 设置最大高度为500px
    const BORDER_COLOR = '#000000'; // 设置边框颜色
    const BORDER_WIDTH = 2; // 设置边框宽度

    const reader = new FileReader();
    reader.readAsDataURL(file.raw);
    
    reader.onload = (event) => {
      const image = new Image();
      image.src = event.target.result;

      image.onload = () => {
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');

        let width = image.width;
        let height = image.height;

        if (width > MAX_WIDTH || height > MAX_HEIGHT) {
          const aspectRatio = width / height;

          if (width > height) {
            width = MAX_WIDTH;
            height = parseInt(width / aspectRatio);
          } else {
            height = MAX_HEIGHT;
            width = parseInt(height * aspectRatio);
          }
        }

        canvas.width = width;
        canvas.height = height;

        context.drawImage(image, 0, 0, width, height);

        // 绘制边框
        context.strokeStyle = BORDER_COLOR;
        context.lineWidth = BORDER_WIDTH;
        context.strokeRect(0, 0, width, height);

        const resizedImageURL = canvas.toDataURL('image/jpeg', 1.0);
        this.imageUrl = resizedImageURL;
      };
    };
  },
    beforeUpload(file) {
      // 添加对文件类型、大小等的限制以及其他验证逻辑
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件');
      }

      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB');
      }

      return isImage && isLt2M;
    }
  }
};
</script>

<style scoped>
p{
  color: #cccccc;
}
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.upload-demo {
  margin-bottom: 20px;
}

.image-container {
  border: 2px dashed #cccccc;
  padding: 10px;
  position: relative;
  width: 600px;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>